package com.tyc.flink;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.redis.RedisSink;
import org.apache.flink.streaming.connectors.redis.common.config.FlinkJedisPoolConfig;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommand;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommandDescription;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisMapper;
import org.apache.flink.util.Collector;

import java.util.Arrays;

/**
 * 将计算结果输出到redis
 *
 * @author tyc
 * @version 1.0
 * @date 2022-11-17 09:41:02
 */
public class Sink_4_Redis {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<String> streamSource = env.fromCollection(Arrays.asList(
                "hello c",
                "hello java",
                "hello golang",
                "hello python",
                "hello js"
        ));
        // 配置redis
        FlinkJedisPoolConfig config = new FlinkJedisPoolConfig.Builder()
                .setHost("10.1.1.91")
                .setPort(6379)
                .setPassword("111111")
                .setDatabase(1)
                .build();

        SingleOutputStreamOperator<Tuple2<String, Integer>> sum = streamSource
                .flatMap(new MyStreamFlatMap())
                .keyBy(item -> item.f0)
                .sum(1);
        sum.print();
        sum.addSink(new RedisSink(config, new MyRedisMapper()));
        env.execute();
    }

    private static class MyStreamFlatMap implements FlatMapFunction<String, Tuple2<String, Integer>> {
        @Override
        public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
            String[] words = s.split(" ");
            for(String word:words) {
                collector.collect(new Tuple2<>(word,1));
            }
        }
    }

    public static class MyRedisMapper implements RedisMapper<Tuple2<String,Integer>>{

        @Override
        public RedisCommandDescription getCommandDescription() {
            return new RedisCommandDescription(RedisCommand.HSET, "word_count");
        }

        @Override
        public String getKeyFromData(Tuple2<String, Integer> stringIntegerTuple2) {
            return stringIntegerTuple2.f0;
        }

        @Override
        public String getValueFromData(Tuple2<String, Integer> stringIntegerTuple2) {
            return String.valueOf(stringIntegerTuple2.f1);
        }
    }
}
